console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { startZeroReport,checkZeroReport } from './zeroReport.js';


let baseInfoCache;

$(document).ready(function () {
  // 发送获得零申报数据事件
  window.postMessage(
    {
      event: 'getZeroInfo'
    },
    '*'
  );
  checkZeroReport();

  let pathName = window.location.pathname;
  // 登录填写账号密码
  if (/\/sso\/login/g.test(pathName)) {
    window.postMessage({
      event: 'getBaseInfo'
    }, '*');
  }
  if (/\/portal\/index.do/g.test(pathName)) {
    let $contentiframe = $('#contentiframe');
    if ($contentiframe.length > 0) {
      $('#contentiframe')[0].contentWindow.location.reload(true);
      $('#contentiframe').on('load', function () {
        $('#contentiframe')[0].contentWindow.openMaxWindow = function (url) {
          window.open(url);
        };
      });
    }
  }

  if (/\/portal\/include.do/g.test(pathName)) {
    let url = $('#contentiframe').attr('src');
    window.location.href = url;
  }

  // if(/\/shenbao\/index.action/g.test(pathName)) {
  //   getPeriodAndType();
  // }
});

window.onload = function() {

};


window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    data = data.data;
    let sheet = data.saasData.sheet;
    if (sheet == 'sds' || sheet == 'zzs') {
      fillInput(data);
    } else {
      fillInput(await transformDataByOpenWeb(data));
    }
  }
  if (data.event === 'getNationData') {
    getNationData(data.data.taxType);
  }
  if (data.event === 'getBaseInfo') {
    baseInfoCache = data.data;
    autoInputAccount(baseInfoCache);
  }
  if (data.event === 'getZeroInfoBack') {
    let backInfo = await startZeroReport(data);
  }
  if (data.event === "zeroReportEnd") {
    //console.log(data.data.data.isSuccess);
    if(data.data.data.isSuccess){
      setTimeout(() => {
        window.postMessage(
          {
            event: "asyncTableDetailRequest"
          },
          "*"
        );
      }, 100);
    }
    setTimeout(()=>{
      window.postMessage(
        {
          event: 'clearZeroReport'
        },
        '*'
      );
      window.sessionStorage.clear();
      document.cookie = "GDS_PORTAL_NSRSBH='';expires=0;path=/";
      window.location.href = "/portal/loginout.do";
    },3000)
  }
  if (data.event === "asyncTableDetailRequestEnd") {
    // setTimeout(() => {
    //   sessionStorage.gotologin = "Y";
    //   sessionStorage.removeItem("changeCompany");
    //   sessionStorage.removeItem("dsChangeCompany");
    //   // eslint-disable-next-line no-useless-concat
    //   window.location.href = "/" + "zjgfdzswj" + "/main/logout.jsp";
    // }, 1000);
  }
  if (data.event === 'baoBiaoDetailBack') {
    if (data.data.type === 'yhs') {
      setTimeout(() => {
        window.sessionStorage.setItem('yhs', true);
        window.location.reload();
      }, 2000);
    }
  }
}, false);

/**
 * 获取公司信息
 */
function getNationData(taxType) {
  let taxInfo = {
    institution: getGsInstitution() === 'small' ? '2013' : '2007', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: ''// 税款所属期止
  };

  if (taxType === 'hsqj' && isHsqjSmall()) {
    taxInfo.isHsqjSmall = true;
  }

  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

/**
 * 判断是否为小微企业 汇算清缴
 */
function isHsqjSmall() {
  const iframe = getHsqjIframe();
  if (iframe) {
    const title = iframe.contentWindow.document.querySelector('.dbt').innerText || '';
    return !title.includes('一般企业');
  }
  return false;
}

function getHsqjIframe() {
  return $('body').find('.panel iframe:visible')[0];
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  $('[name="username"]').val(companyInfo.nationalTaxAccount || companyInfo.nationalTaxId).trigger('change');
  $('input:password').val(companyInfo.nationalTaxPass).trigger('change');
}

function fillInput({ saasData, baseInfo }) {
  let iframeWindow;
  const {
    lastYearData, isYearReport, sheetType, sheet
  } = saasData;
  iframeWindow = $('#mainIframe')[0].contentWindow;

  let message = '填报成功';
  try {
    let inputData = saasData.data;
    if (sheet === 'sds') {
      inputData = delSdsData(inputData.openParams.inputData.data.profit, baseInfo.companyInfo.institutionCode);
    }

    if (isYearReport) {
      inputData = hackYearReportInput(inputData, lastYearData, sheet);
    }

    for (let key in inputData) {
      let value = Number.parseFloat(inputData[key]).toFixed(2) || '0.00';
      if (iframeWindow.$(`[name$="${key}"]`).length != 0) {
        iframeWindow.$(`[name$="${key}"]`).val(value).trigger('change');
      }
    }
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message
    }
  }, '*');
}

/**
 * hack年报填写数据 年报字段有变化
 * @param inputData 本年数据
 * @param lastYearData 上年数据
 * @param sheet 报表类型
 * @returns {{}}
 */
function hackYearReportInput(inputData, lastYearData, sheet) {
  let keys = Object.keys(lastYearData);
  let results = keys.reduce((result, key) => {
    if (['profit', 'cash'].includes(sheet)) {
      if (key.includes('byje')) {
        result[key.replace('byje', 'snje')] = lastYearData[key.replace('byje', 'bnljje')];
      }
    }
    return result;
  }, {});
  return { ...inputData, ...results };
}

function delSdsData(tableData, institutionCode) {
  let sdsData = {};
  if (institutionCode == 1) {
    sdsData = {
      yysrbnljje: tableData.SQJE_1_1,
      yycbbnljje: tableData.SQJE_1_2,
      lrzebnljje: tableData.SQJE_1_15
    };
  } else {
    sdsData = {
      yysrbnljje: tableData.BNLJJE_1,
      yycbbnljje: tableData.BNLJJE_2,
      lrzebnljje: tableData.BNLJJE_30
    };
  }

  return sdsData;
}

let getGsInstitution = function () {
  let gsInstitution = 'small';
  let text = $('#mainIframe').contents().find('#selectItem').text();
  if (text.trim().search('适用执行企业会计准则') != -1) {
    gsInstitution = 'gener';
  } else if (text.trim().search('适用执行小企业会计准则') != -1) {
    gsInstitution = 'small';
  }
  return gsInstitution;
};

function getPeriodAndType() {
  $('#mainIframe').on('load', function () {
    let $this = $(this);
    let urlObj = url2json($this.attr('src')) || {};
    let sssq_q = urlObj.sssq_q.substr(0, 7),
      sssq_z = urlObj.sssq_z.substr(0, 7);
    let contentWindow = $this[0].contentWindow;
    let tableName = contentWindow.$('.dbt').text() || ' ';
    let type = 'balance';

    if (tableName.search('资产负债表') != -1) {
      type = 'balance';
    } else if (tableName.search('利润表') != -1) {
      type = 'profit';
    } else if (tableName.search('现金流量表') != -1) {
      type = 'cash';
    }
    // setIntervalFn && window.clearInterval(setIntervalFn);
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: type,
        startTime: sssq_q,
        endTime: sssq_z
      }
    }, '*');
  });
}

function url2json(url) {
  let index = -1,
    str = '',
    arr = [],
    length = 0,
    res = {};
  if (url.indexOf('?') != -1) {
    index = url.indexOf('?');
    str = url.substring(index + 1);
    arr = str.split('&');
    length = arr.length;
    for (let i = 0; i < length; i++) {
      res[arr[i].split('=')[0]] = arr[i].split('=')[1];
    }
  } else {
    res = {};
  }
  return res;
}
